<?php
/**
 * @deprecated (使用下面的v2版本)
 * @see \App\Http\Controllers\App\RecommendProductV2Controller
 * 推荐商品的管理
 * Author: lyun
 * Date: 2018/4/12
 * Created by Panxsoft.
 */

namespace App\Http\Controllers\App;

use App\Http\Requests\App\RecommendProductIndexRequest;
use App\Models\Panx\Product;
use App\Models\Panx\ProductTag;
use App\Models\Store\Store;
use App\Services\Repositories\Product\ProductRepository;
use App\Services\Repositories\Product\DeprecatedRecommendProductRepository;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use App\Services\Utils\Guard;
use App\Services\Utils\PanxCollection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use App\Http\Controllers\Controller;

/**
 * @deprecated - App 接口不清理
 *
 * Class RecommendProductController
 *
 * @package App\Http\Controllers\App
 */
class RecommendProductController extends Controller
{
    use ApiResponser,
        ApiChecker;

    const ROUTES = [
        'index'   => 'app.recommend-product.index',
    ];

    /**
     * 根据肤质检测报告，推荐商品
     * @test
     *
     * @param RecommendProductIndexRequest $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(RecommendProductIndexRequest $request)
    {
        $tag_ids = (new DeprecatedRecommendProductRepository)->getTagIds($request);

        $recommend_products = $this->getProductsByTags($tag_ids, $request->sex);

        $recommend_products = $this->assembleProducts($recommend_products);

        return $this->response(compact('recommend_products'));
    }

    /**
     * @param array $tag_ids
     * @param  $sex
     * @return Collection|static[]
     */
    private function getProductsByTags(array $tag_ids, $sex)
    {
        /** @var Store $store */
        $store = Guard::deviceAccount()->store;

        $recommend_products = (new Product)
            ->filterSex($sex)
            ->filterStoreProductType($store, Product::STORE_CUSTOMER_PRODUCT)
            ->whereNotIn('products.id', ProductRepository::getStoreCustomerDeletedProductIds($store))
            ->whereHas('productTags', function (Builder $query) use ($tag_ids) {
                $query->whereIn(((new ProductTag)->getTable()) . '.id', $tag_ids);
            })
            ->with('thumbImage', 'productTags')
            ->inRandomOrder()
            ->limit(rand(5, 10))
            ->get();

        return $recommend_products;
    }

    /**
     * @param Collection $recommend_products
     * @return Collection
     */
    private function assembleProducts(Collection $recommend_products)
    {
        (new PanxCollection($recommend_products))
            ->eachAppend(['tag_names', 'thumb_url', 'link_product'])
            ->makeHidden(['thumbImage', 'productTags']);

        return $recommend_products;
    }
}
